<template>
    <div class="x-cascade-address" @click="handleClick">
        <cube-input :value="valueText" :placeholder="placeholder" disabled></cube-input>
    </div>
</template>

<script>
import Address from 'src/api/address';

export default {
    props: {
        value: {
            type: String,
            default: '',
        },
        placeholder: {
            type: String,
            default: '',
        },
        disabled: {
            type: Boolean,
            default: false
        }
    },
    data() {
        return {
            picker: null
        };
    },
    computed: {
        /**
             * 外部只传一个最小地址的id，需要从缓存里读取补充上级和中文
             */
        valueText() {
            if (this.value) {
                return Address.replace(this.value);
            }
            return '';
        }
    },
    methods: {
        getData() {
            console.log(new Date());
            let data = Address.getTree();
            console.log(new Date());
            return data;
        },
        /**
         * 根据传入的区县id，确认级联index
         * @returns {Array}
         */
        getValueIndex() {
            if (!this.value) {
                return [0];
            }
            let tree = Address.getTree();
            let code = this.value;
            let cascade = Address.getCascade(code);
            // 确定省份index
            let provinceIndex = tree.findIndex(item => item.code === cascade.parent.parent.code);
            // 确定城市
            let cities = tree[provinceIndex].children;
            // 确定城市index
            let cityIndex = cities.findIndex(item => item.code === cascade.parent.code);
            // 确定区县index
            let zones = cities[cityIndex].children;
            let zoneIndex = zones.findIndex(item => item.code === cascade.code);
            return [provinceIndex, cityIndex, zoneIndex];
        },
        handleClick() {
            if (this.disabled) {
                return;
            }
            // 单例模式
            if (this.picker) {
                this.picker.show();
            } else {
                this.picker = this.$createCascadePicker({
                    title: '地区选择',
                    data: this.getData(),
                    selectedIndex: this.getValueIndex(),
                    alias: { value: 'code', text: 'name' },
                    onSelect: this.handleSelect,
                    onCancel: this.handleCancel
                }).show();
            }
        },
        handleSelect(value, index, text) {
            // 只反馈最小地址
            this.$emit('input', value[2]);
        },
        handleCancel() {
            console.debug('cancel');
        }
    }
};
</script>

<style scoped>

</style>